package com.changgou.seckill.thread;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.Future;

@Component
public class MultiThreadingCreateOrder {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private IdWorker idWorker;

    /***
     * 多线程下单操作
     */
    @Async
    public Future<String> createOrder() {

        SeckillStatus seckillStatus = (SeckillStatus) redisTemplate.boundListOps("seckillQueue").rightPop();

        if (seckillStatus == null)
            return new AsyncResult("没有状态值");

        String username = seckillStatus.getUsername();
        Long id = seckillStatus.getGoodsId();
        String time = seckillStatus.getTime();

        // 下单，需要从队列中减掉（弹pop）一个商品id
        Object goods = redisTemplate.boundListOps("SeckillGoodsCountList_" + id).rightPop();
        if (goods == null) {
            //删除重复排队信息
            redisTemplate.boundHashOps("UserQueueCount_" + username).delete(id);
            //删除状态
            redisTemplate.boundHashOps("UserQueueStatus_" + username).delete(id);
            //说明卖完了
            // throw new RuntimeException("对不起,已售罄!");
            return new AsyncResult("对不起,已售罄");
        }


        //获取商品数据
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(id);

        //如果没有库存，则直接抛出异常
        if (seckillGoods == null || seckillGoods.getStockCount() <= 0) {
            //  throw new RuntimeException("对不起,已售罄!");
            return new AsyncResult("对不起,已售罄");

        }
        //如果有库存，则创建秒杀商品订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());                 // 订单id
        seckillOrder.setSeckillId(id);                         // 秒杀商品id
        seckillOrder.setMoney(seckillGoods.getCostPrice());    // 支付金额
        seckillOrder.setUserId(username);                      // 用户
        seckillOrder.setCreateTime(new Date());               // 下单日期
        seckillOrder.setStatus("0");                           //下单状态 0 未支付  1已支付

        //将秒杀订单存入到Redis中
        redisTemplate.boundHashOps("SeckillOrder_" + username).put(seckillOrder.getId(), seckillOrder);

        //库存减少
        // seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        Long stockCount = redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillGoods.getId()).size();//库存量

        //判断当前商品是否还有库存
        //    if (seckillGoods.getStockCount() <= 0) {

        if (stockCount <= 0) {
            //并且将商品数据同步到MySQL中
            seckillGoods.setStockCount(stockCount.intValue());
            seckillGoodsMapper.updateByPrimaryKeySelective(seckillGoods);

            //如果没有库存,则清空Redis缓存中该商品
            redisTemplate.boundHashOps("SeckillGoods_" + time).delete(id);
        } else {
            //如果有库存，则直数据重置到Reids中
            redisTemplate.boundHashOps("SeckillGoods_" + time).put(id, seckillGoods);

        }
        //抢单成功！
        seckillStatus.setStatus(2);//等待支付
        seckillStatus.setOrderId(seckillOrder.getId());
        seckillStatus.setMoney(Float.valueOf(seckillOrder.getMoney()));
        redisTemplate.boundHashOps("UserQueueStatus_" + username).put(seckillOrder.getId(), seckillStatus);
        return new AsyncResult(null);
    }
}